import domain from './domain.js';

/**
 * 接口请求
 * @param {String} url  	// 接口地址
 * @param {Object} data  	// 请求参数 
 * @param {String} method  	// 请求方式 
 * */
const request = (url, data = {}, method = 'GET') => {
	
	url = `http://localhost:9000${url}`;

	return new Promise((resolve, reject) => {
		uni.request({
			url,
			data,
			method,
			header: {},
			success(res) {
				resolve(res.data);
			},
			fail(err) {
				reject('');
			}
		})
	})
}


/**
 * 函数防抖
 * @params {Function} fn 函数事件
 * @param {String} delay 等待时间
 * @isClick {Boolean} isClick 是否点击事件 开始时会立即执行
 * */
function debounce(fn, delay = 200, isClick = false) {
	let timer = null;
	let times = 0;
	if (typeof delay === 'boolean') {
		isClick = delay;
		delay = 200;
	}
	return function() {
		times++;
		if (times === 1 && isClick) {
			fn.apply(this, arguments);
		}
		timer && clearTimeout(timer);
		timer = setTimeout(() => {
			if (!isClick) {
				fn.apply(this, arguments);
			}
			times = 0;
		}, delay);
	}
}

/**
 * 函数节流
 * @params {Function} fn 函数事件
 * @param {String} delay 等待时间
 * */
function throttle(fn, delay = 100) {
	let timer = null;
	return function() {
		if (!timer) {
			timer = setTimeout(() => {
				timer = null;
				fn.apply(this, arguments);
			}, delay)
		}
	}
}

/**
 * 时间戳转时间
 * 毫秒
 */
function timeStampToTime(timestamp) {
	var now = new Date(timestamp),
		y = now.getFullYear(),
		m = now.getMonth() + 1,
		d = now.getDate();
	return y + "/" + (m < 10 ? "0" + m : m) + "/" + (d < 10 ? "0" + d : d) + " " + now.toTimeString().substr(0, 8);
}

/**
 * 单一数组去重 → ["",""]
 * @array 传入的数组
 * */
function delRepeat(array) {
	if (!(array instanceof Array)) {
		console.warn("你传入的不是数组类型");
		return false;
	}
	//去重的方法有很多，我选择了这一种
	var result = [];
	for (var i = 0; i < array.length; i++) {
		if (result.indexOf(array[i]) === -1) {
			result.push(array[i]);
		}
	}
	return result;
}

/**
 * 数组中Json数据去重 → [{},{}]
 * @array 传入的数组
 * @attrName 属性名，用json数据中的什么属性名判断是否重复
 * */
function delRepeatJson(array, attrName) {
	if (!(array instanceof Array)) {
		console.warn("你传入的不是数组类型");
		return false;
	}
	var temp = {}; //用于name判断重复
	var result = []; //最后的新数组
	array.map(function(item, index) {
		if (!temp[item[attrName]]) {
			result.push(item);
			temp[item[attrName]] = true;
		}
	});

	return result;
}

/**
 * 过滤表情字符
 * @param {String} value
 * @return {String} value
 * */
function filterEmoji(value) {
	let regx =
		/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]|[\uD800-\uDBFF]|[\uDC00-\uDFFF]|[^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n]/g;
	let newValue = value.replace(regx, '');
	return newValue;
}

module.exports = {
	request,
	debounce,
	throttle,
	timeStampToTime,
	delRepeat,
	delRepeatJson,
	filterEmoji
}
